package net.sourceforge.jweb.maven.mojo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Properties;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * Create a Properties file
 * 
 * @author maoanapex88@163.com
 */
@Mojo(name = "write-properties-file", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true)
public class WritePropertiesFileMojo extends AbstractMojo {

	/**
	 * Output directory (defaults to ${project.build.outputDirectory})
	 */
	@Parameter(property = "outputDirectory", defaultValue = "${project.build.outputDirectory}", required = true)
	private File outputDirectory;

	/**
	 * Filename where the properties are saved
	 */
	@Parameter(property = "filename", required = true)
	private String filename;

	/**
	 * Properties to save
	 */
	@Parameter(property = "properties", required = true)
	private Properties properties;

	/**
	 * Comment for properties file
	 */
	@Parameter(property = "comment", defaultValue = "Generated by write-property-file Maven plugin")
	private String comment;

	/**
	 * Create intermediate directories if necessary (defaults to true)
	 */
	@Parameter(property = "createDirectory", defaultValue = "true")
	private boolean createDirectory;

	public void execute() throws MojoExecutionException, MojoFailureException {
		System.out.println(outputDirectory+","+filename);
		File finalFile = new File(outputDirectory, filename).getAbsoluteFile();
		String finalFilename = finalFile.getAbsolutePath();
		File finalDirectory = finalFile.getParentFile();
		String finalDirectoryName = finalDirectory.getAbsolutePath();

		if (!finalDirectory.exists()) {
			getLog().info("Creating directory " + finalDirectoryName);
			finalDirectory.mkdirs();
		}

		getLog().info("Saving properties to file " + finalFilename);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(finalFile);
			OutputStreamWriter writer = new OutputStreamWriter(out, Charset.forName("UTF-8"));

			String finalComment = comment;
			if (comment != null && comment.trim().isEmpty()) {
				finalComment = null;
			}
			properties.store(writer, finalComment);
			writer.close();
			out.close();
		} catch (IOException e) {
			throw new MojoFailureException("Unable to save properties to file " + finalFilename + ": " + e.getMessage(), e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					// Ignore
				}
			}
		}
	}

}